package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.SalesTop10ReportList;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class reportSeriveImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistic(LocalDate begin, LocalDate end) {
        //计算横坐标 —— 时间 放在一个list集合中
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        //计算纵坐标 --每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime begin1 = LocalDateTime.of(date, LocalTime.MIN);//将日期和最小的时间拼接
            LocalDateTime end1 = LocalDateTime.of(date, LocalTime.MAX);//将日期和最大的时间拼接
            Double sum = orderMapper.turnoverStatistic(begin1,end1, Orders.COMPLETED); //已完成的订单
            if(sum==null){
                sum = 0.0;
            }
            turnoverList.add(sum);
        }
        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return build;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistic(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime begin1 = LocalDateTime.of(begin,LocalTime.MIN);
            LocalDateTime end1 = LocalDateTime.of(date, LocalTime.MAX);//将日期和最大的时间拼接
            Integer sigleCount = userMapper.selectByTime(begin1, end1); //当日新增用户
            newUserList.add(sigleCount);
            Integer totalCount = userMapper.selectBeforeOnDay(end1);    //至某天为止的所有用户数量
            totalUserList.add(totalCount);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 统计指定区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            // 日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        // 查询每天的有效订单数，和订单总数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 查询每天的订单总数 select count(id) form orders where order_time > beginTime and order_time < endTime
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            // 查询每天的有效订单数 select count(id) form orders where order_time > beginTime and order_time < endTime and Status = 5
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        // 计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        // 计算区时间间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        // 计算订单完成率
        Double OrderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            OrderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(OrderCompletionRate)
                .build();
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status){
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }


    @Override
    public SalesTop10ReportVO saleTop10(LocalDate begin, LocalDate end) {
        LocalDateTime begin1 = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime end1 = LocalDateTime.of(end,LocalTime.MAX);
        //查询在这个时间段内已支付的所有订单
        List<Integer> list = orderMapper.queryOrderByTime(begin1, end1, Orders.PAID);
        //根据订单id查询订单明细表，得出销量排名前十的套餐或菜品，封装在list集合中
        List<SalesTop10ReportList> salesTop10ReportLists = orderDetailMapper.queryOrderDetailByIds(list);
        List<String> names = new ArrayList(); //存名字
        List<Long> numbers = new ArrayList(); //存数量
        for (SalesTop10ReportList salesTop10ReportList : salesTop10ReportLists) {
            names.add(salesTop10ReportList.getName());
            numbers.add(salesTop10ReportList.getNumber());
        }
        return SalesTop10ReportVO.builder().
                nameList(StringUtils.join(names,",")).
                numberList(StringUtils.join(numbers,",")).
                build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //计算时间--近30天
        LocalDate start = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //获取近三十天的相关数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //通过类加载器获得模版文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //通过模版文件创建excel文件到内存中
        try {
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            //获取sheet
            XSSFSheet sheet = excel.getSheet("sheet1");
            //设置报表时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+start+"至"+end);
            //设置其他数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            int rowNum = 7;
            //设置详细数据
            while (!start.equals(end)){
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(start, LocalTime.MAX));
                XSSFRow row = sheet.getRow(rowNum);
                row.getCell(1).setCellValue(start.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
                rowNum++;
                start = start.plusDays(1);
            }
            //设置最后一天数据
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(start, LocalTime.MAX));
            XSSFRow row = sheet.getRow(rowNum);
            row.getCell(1).setCellValue(start.toString());
            row.getCell(2).setCellValue(businessData1.getTurnover());
            row.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData1.getUnitPrice());
            row.getCell(6).setCellValue(businessData1.getNewUsers());


            //创建输出流到客户端
            ServletOutputStream out = response.getOutputStream();
            //将excel写出到客户端
            excel.write(out);
            //关闭资源
            excel.close();
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

